import React, { useState, useEffect, Component, ErrorInfo, ReactNode } from 'react';
import { 
  Card, 
  Table, 
  Button, 
  Modal, 
  Space, 
  Avatar, 
  Tag, 
  message,
  QRCode,
  Spin,
  Select,
  Row,
  Col,
  Layout,
  Tabs,
  List,
  Typography,
  Dropdown,
  Divider
} from 'antd';
import { 
  LoginOutlined, 
  LogoutOutlined, 
  QrcodeOutlined,
  UserOutlined,
  PlusOutlined,
  GlobalOutlined,
  MoreOutlined,
  DownOutlined,
  UpOutlined
} from '@ant-design/icons';

const { Text } = Typography;
import { useElectronAPI } from '../hooks/useElectronAPI';

// 错误边界组件
interface ErrorBoundaryState {
  hasError: boolean;
  error?: Error;
}

class ErrorBoundary extends Component<{children: ReactNode}, ErrorBoundaryState> {
  constructor(props: {children: ReactNode}) {
    super(props);
    this.state = { hasError: false };
  }

  static getDerivedStateFromError(error: Error): ErrorBoundaryState {
    // 更新 state 使下一次渲染能够显示降级后的 UI
    return { hasError: true, error };
  }

  componentDidCatch(error: Error, errorInfo: ErrorInfo) {
    // 记录错误信息
    console.error('[ErrorBoundary] 捕获到渲染错误:', error, errorInfo);
  }

  render() {
    if (this.state.hasError) {
      // 自定义降级后的 UI
      return (
        <div style={{ padding: '20px', textAlign: 'center' }}>
          <h2>页面渲染出现错误</h2>
          <p>错误信息: {this.state.error?.message}</p>
          <Button 
            type="primary" 
            onClick={() => {
              this.setState({ hasError: false, error: undefined });
              window.location.reload();
            }}
          >
            重新加载页面
          </Button>
        </div>
      );
    }

    return this.props.children;
  }
}

// 定义类型接口
interface Account {
  id: string;
  platformId: string;
  username: string;
  createdAt: string;
}

interface Platform {
  id: string;
  name: string;
  color: string;
}

interface QRData {
  sessionId: string;
  qrCode: string;
}

const AccountsPage: React.FC = () => {
  const [accounts, setAccounts] = useState<Account[]>([]);
  const [loading, setLoading] = useState<boolean>(false);
  const [qrModalVisible, setQrModalVisible] = useState<boolean>(false);
  const [qrData, setQrData] = useState<QRData | null>(null);
  const [scanning, setScanning] = useState<boolean>(false);
  const [selectedPlatform, setSelectedPlatform] = useState<string>('');
  const [addAccountModalVisible, setAddAccountModalVisible] = useState<boolean>(false);
  const [selectedPlatformForAdd, setSelectedPlatformForAdd] = useState<string>('');
  const [browserTabs, setBrowserTabs] = useState<{key: string, title: string, url: string}[]>([]);
  const [activeTabKey, setActiveTabKey] = useState<string>('');
  const [webviewKey, setWebviewKey] = useState<number>(0); // 用于强制webview重新渲染
  const [containerDimensions, setContainerDimensions] = useState<{width: number, height: number}>({width: 0, height: 0}); // 容器尺寸状态
  const [webviewLoading, setWebviewLoading] = useState<{[key: string]: boolean}>({}); // webview加载状态
  const [webviewError, setWebviewError] = useState<{[key: string]: boolean}>({}); // webview错误状态
  const [renderError, setRenderError] = useState<string | null>(null); // 渲染错误状态

  const electronAPI = useElectronAPI();

  // 错误边界处理
  useEffect(() => {
    const handleError = (error: ErrorEvent) => {
      console.error('[AccountsPage] 渲染错误:', error);
      setRenderError(error.message || '未知错误');
    };

    const handleUnhandledRejection = (event: PromiseRejectionEvent) => {
      console.error('[AccountsPage] Promise 拒绝:', event.reason);
      setRenderError('异步操作失败: ' + (event.reason?.message || event.reason));
    };

    window.addEventListener('error', handleError);
    window.addEventListener('unhandledrejection', handleUnhandledRejection);

    return () => {
      window.removeEventListener('error', handleError);
      window.removeEventListener('unhandledrejection', handleUnhandledRejection);
    };
  }, []);

  useEffect(() => {
    loadAccounts();
  }, []);

  // 添加窗口大小变化监听，确保webview能够响应窗口大小变化
  useEffect(() => {
    let resizeTimer: NodeJS.Timeout;
    let isInitialized = false; // 防止初始化时重复触发
    
    const handleResize = () => {
      // 清除之前的定时器，防止频繁触发
      if (resizeTimer) {
        clearTimeout(resizeTimer);
      }
      
      // 延迟执行以确保DOM更新完成，使用防抖机制
      resizeTimer = setTimeout(() => {
        // 获取当前容器尺寸
        const container = document.querySelector('.ant-col:nth-child(2)');
        if (container) {
          const rect = container.getBoundingClientRect();
          const newDimensions = {width: rect.width, height: rect.height};
          
          // 只有在尺寸真正发生变化时才更新状态
          setContainerDimensions(prev => {
            if (prev.width !== newDimensions.width || prev.height !== newDimensions.height) {
              return newDimensions;
            }
            return prev;
          });
        }
        
        // 只有在非初始化状态且有webview时才更新key
        if (isInitialized && document.querySelectorAll('webview').length > 0) {
          setWebviewKey(prev => prev + 1);
          
          // 强制重新计算webview尺寸和布局
          setTimeout(() => {
            const webviews = document.querySelectorAll('webview');
            webviews.forEach(webview => {
              if (webview && typeof (webview as any).executeJavaScript === 'function') {
                // 触发webview内容重新布局
                (webview as any).executeJavaScript(`
                  // 强制重新计算页面布局
                  window.dispatchEvent(new Event('resize'));
                  // 确保页面内容适应新的视口尺寸
                  if (document.body) {
                    document.body.style.zoom = '1';
                    document.body.style.transform = 'scale(1)';
                  }
                  if (document.documentElement) {
                    document.documentElement.style.zoom = '1';
                    document.documentElement.style.transform = 'scale(1)';
                  }
                  // 触发页面重新布局
                  const event = new Event('orientationchange');
                  window.dispatchEvent(event);
                `).catch(console.warn); // 忽略可能的执行错误
              }
            });
          }, 100); // 额外延迟确保webview完全加载
        }
        
        // 标记已初始化
        isInitialized = true;
      }, 300); // 增加防抖延迟时间
    };

    // 监听窗口大小变化事件
    window.addEventListener('resize', handleResize);
    
    // 初始化容器尺寸（延迟执行避免初始渲染冲突）
    setTimeout(handleResize, 100);
    
    // 清理事件监听器和定时器
    return () => {
      window.removeEventListener('resize', handleResize);
      if (resizeTimer) {
        clearTimeout(resizeTimer);
      }
    };
  }, []); // 空依赖数组，确保只执行一次

  const loadAccounts = async () => {
    setLoading(true);
    try {
      console.log('[AccountsPage] 开始加载账号列表...');
      const data = await electronAPI.getAccounts();
      console.log('[AccountsPage] 成功加载账号列表:', data);
      setAccounts(data || []); // 确保data不为null或undefined
    } catch (error) {
      console.error('[AccountsPage] 加载账号列表失败:', error);
      message.error('加载账号列表失败: ' + (error as Error).message);
      setAccounts([]); // 设置为空数组避免渲染错误
    } finally {
      setLoading(false);
    }
  };

  const handleLogin = async (platform: string) => {
    try {
      setSelectedPlatform(platform);
      setScanning(true);
      
      const result = await electronAPI.startQRLogin(platform);
      setQrData(result);
      setQrModalVisible(true);
      
      // 开始轮询登录状态
      pollLoginStatus(result.sessionId);
      
    } catch (error) {
      message.error('登录失败: ' + (error as Error).message);
      setScanning(false);
    }
  };

  const pollLoginStatus = async (sessionId: string) => {
    const checkStatus = async () => {
      try {
        const status = await electronAPI.getLoginStatus(sessionId);
        
        if (status.status === 'success') {
          message.success('登录成功！');
          setQrModalVisible(false);
          setScanning(false);
          await loadAccounts();
        } else if (status.status === 'failed') {
          message.error('登录失败');
          setQrModalVisible(false);
          setScanning(false);
        } else {
          // 继续轮询
          setTimeout(checkStatus, 2000);
        }
      } catch (error) {
        console.error('Failed to check login status:', error);
        setScanning(false);
      }
    };
    
    checkStatus();
  };

  const handleLogout = async (accountId: string) => {
    try {
      await electronAPI.removeAccount(accountId);
      message.success('已退出登录');
      await loadAccounts();
    } catch (error) {
      message.error('退出登录失败: ' + (error as Error).message);
    }
  };

  // 处理添加账号按钮点击
  const handleAddAccount = () => {
    setAddAccountModalVisible(true);
  };

  // 处理平台选择确认
  const handlePlatformConfirm = async () => {
    if (!selectedPlatformForAdd) {
      message.warning('请选择一个平台');
      return;
    }

    try {
      console.log(`[AccountsPage] 正在获取登录URL，平台: ${selectedPlatformForAdd}`);
      
      // 检查electronAPI是否可用
      if (!electronAPI || typeof electronAPI.openBrowserLogin !== 'function') {
        throw new Error('Electron API 不可用，请确保应用程序正确启动');
      }
      
      // 获取登录URL
      const result = await electronAPI.openBrowserLogin(selectedPlatformForAdd);
      console.log(`[AccountsPage] 获取登录URL成功:`, result);
      
      // 验证返回结果
      if (!result || !result.loginUrl) {
        throw new Error('获取登录URL失败：返回结果无效');
      }
      
      // 在右侧区域新增标签页显示登录页面
      const newTabKey = `login-${selectedPlatformForAdd}-${Date.now()}`;
      const newTab = {
        key: newTabKey,
        title: `${selectedPlatformForAdd}登录`,
        url: result.loginUrl
      };
      
      // 防止重复添加相同的标签页
      setBrowserTabs(prev => {
        const existingTab = prev.find(tab => tab.url === result.loginUrl);
        if (existingTab) {
          setActiveTabKey(existingTab.key);
          return prev;
        }
        return [...prev, newTab];
      });
      
      setActiveTabKey(newTabKey);
      setAddAccountModalVisible(false);
      setSelectedPlatformForAdd('');
      message.success('登录页面已在右侧显示，请完成登录...');
      
      // 使用ref来存储interval ID，避免闭包问题
      let checkInterval: NodeJS.Timeout | null = null;
      let isChecking = false;
      
      const startChecking = () => {
        if (isChecking) return; // 防止重复启动检查
        isChecking = true;
        
        checkInterval = setInterval(async () => {
          try {
            await loadAccounts();
          } catch (error) {
            console.error('[AccountsPage] 定期检查账号失败:', error);
          }
        }, 5000); // 增加检查间隔到5秒，减少频率
        
        // 10分钟后停止检查
        setTimeout(() => {
          if (checkInterval) {
            clearInterval(checkInterval);
            checkInterval = null;
            isChecking = false;
          }
        }, 600000);
      };
      
      // 延迟启动检查，避免立即执行
      setTimeout(startChecking, 2000);
      
    } catch (error) {
      console.error(`[AccountsPage] 获取登录URL失败:`, error);
      const errorMessage = error instanceof Error ? error.message : '未知错误';
      message.error('获取登录URL失败: ' + errorMessage);
      // 移除setRenderError调用，避免触发重新渲染
      console.error('添加账号失败:', errorMessage);
    }
  };

  const platforms: Platform[] = [
    { id: 'douyin', name: '抖音', color: '#000' },
    { id: 'bilibili', name: '哔哩哔哩', color: '#00a1d6' },
    { id: 'xiaohongshu', name: '小红书', color: '#ff2442' }
  ];

  // 按平台分组账号
  const groupedAccounts = platforms.reduce((groups, platform) => {
    const platformAccounts = accounts.filter(account => account.platformId === platform.id);
    if (platformAccounts.length > 0) {
      groups[platform.id] = {
        platform,
        accounts: platformAccounts,
        collapsed: false
      };
    }
    return groups;
  }, {} as Record<string, { platform: Platform; accounts: Account[]; collapsed: boolean }>);

  const [collapsedGroups, setCollapsedGroups] = useState<Record<string, boolean>>({});

  // 切换分组折叠状态
  const toggleGroup = (platformId: string) => {
    setCollapsedGroups(prev => ({
      ...prev,
      [platformId]: !prev[platformId]
    }));
  };

  // 渲染账号卡片
  const renderAccountCard = (account: Account) => {
    const platform = platforms.find(p => p.id === account.platformId);
    
    const menuItems = [
      {
        key: 'logout',
        label: '退出登录',
        icon: <LogoutOutlined />,
        danger: true,
        onClick: () => handleLogout(account.id)
      }
    ];

    return (
      <div
        key={account.id}
        style={{
          display: 'flex',
          alignItems: 'center',
          padding: '12px 16px',
          backgroundColor: '#fff',
          borderRadius: '8px',
          border: '1px solid #f0f0f0',
          marginBottom: '8px',
          cursor: 'pointer',
          transition: 'all 0.2s',
        }}
        onMouseEnter={(e) => {
          e.currentTarget.style.backgroundColor = '#fafafa';
          e.currentTarget.style.borderColor = '#d9d9d9';
        }}
        onMouseLeave={(e) => {
          e.currentTarget.style.backgroundColor = '#fff';
          e.currentTarget.style.borderColor = '#f0f0f0';
        }}
      >
        <Avatar 
          size={40} 
          style={{ 
            backgroundColor: platform?.color,
            marginRight: '12px',
            flexShrink: 0
          }}
        >
          {platform?.name[0]}
        </Avatar>
        
        <div style={{ flex: 1, minWidth: 0 }}>
          <div style={{ 
            fontSize: '14px', 
            fontWeight: 500, 
            color: '#262626',
            marginBottom: '4px',
            overflow: 'hidden',
            textOverflow: 'ellipsis',
            whiteSpace: 'nowrap'
          }}>
            {account.username}
          </div>
          <div style={{ 
            fontSize: '12px', 
            color: '#8c8c8c',
            overflow: 'hidden',
            textOverflow: 'ellipsis',
            whiteSpace: 'nowrap'
          }}>
            {account.id}
          </div>
        </div>
        
        <Dropdown
          menu={{ items: menuItems }}
          trigger={['click']}
          placement="bottomRight"
        >
          <Button
            type="text"
            icon={<MoreOutlined />}
            size="small"
            style={{ 
              color: '#8c8c8c',
              flexShrink: 0
            }}
            onClick={(e) => e.stopPropagation()}
          />
        </Dropdown>
      </div>
    );
  };

  // 如果有渲染错误，显示错误信息
  if (renderError) {
    return (
      <div style={{ 
        padding: '24px', 
        height: '100%',
        display: 'flex',
        alignItems: 'center',
        justifyContent: 'center',
        flexDirection: 'column'
      }}>
        <div style={{ 
          textAlign: 'center',
          padding: '40px',
          backgroundColor: '#fff2f0',
          border: '1px solid #ffccc7',
          borderRadius: '8px',
          maxWidth: '500px'
        }}>
          <h3 style={{ color: '#cf1322', marginBottom: '16px' }}>页面渲染错误</h3>
          <p style={{ color: '#8c8c8c', marginBottom: '16px' }}>{renderError}</p>
          <Button 
            type="primary" 
            onClick={() => {
              setRenderError(null);
              window.location.reload();
            }}
          >
            重新加载页面
          </Button>
        </div>
      </div>
    );
  }

  return (
    <div style={{ 
      padding: '24px', 
      height: '100%',  // 改为100%而不是100vh，让父容器控制高度
      boxSizing: 'border-box',
      display: 'flex',
      flexDirection: 'column'
    }}>
      <Row gutter={16} style={{ 
        flex: 1,
        minHeight: 0  // 关键：允许flex子项收缩以适应容器
      }}>
        {/* 左侧账号列表区域 */}
        <Col span={8} style={{ display: 'flex', flexDirection: 'column' }}>
          <Card 
            title="账号列表" 
            style={{ 
              flex: 1,
              display: 'flex',
              flexDirection: 'column'
            }}
            bodyStyle={{ 
              padding: '16px', 
              flex: 1,
              display: 'flex',
              flexDirection: 'column',
              minHeight: 0,
              overflow: 'auto' 
            }}
          >
            <div style={{ marginBottom: '16px' }}>
              <Button
                type="primary"
                icon={<PlusOutlined />}
                onClick={handleAddAccount}
                block
                size="large"
                style={{ borderRadius: '8px' }}
              >
                添加账号
              </Button>
            </div>

            <div style={{ 
              height: 'calc(100vh - 320px)', 
              overflowY: 'auto',
              paddingRight: '4px'
            }}>
              {loading ? (
                <div style={{ textAlign: 'center', padding: '40px 0' }}>
                  <Spin size="large" />
                </div>
              ) : Object.keys(groupedAccounts).length === 0 ? (
                <div style={{ 
                  textAlign: 'center', 
                  padding: '40px 20px',
                  color: '#8c8c8c'
                }}>
                  <UserOutlined style={{ fontSize: '32px', marginBottom: '16px' }} />
                  <div>暂无账号</div>
                  <div style={{ fontSize: '12px', marginTop: '8px' }}>点击上方按钮添加账号</div>
                </div>
              ) : (
                Object.entries(groupedAccounts).map(([platformId, group]) => {
                  const isCollapsed = collapsedGroups[platformId];
                  return (
                    <div key={platformId} style={{ marginBottom: '16px' }}>
                      {/* 分组标题 */}
                      <div
                        style={{
                          display: 'flex',
                          alignItems: 'center',
                          padding: '8px 12px',
                          backgroundColor: '#fafafa',
                          borderRadius: '6px',
                          cursor: 'pointer',
                          marginBottom: '8px',
                          border: '1px solid #f0f0f0'
                        }}
                        onClick={() => toggleGroup(platformId)}
                      >
                        {isCollapsed ? <DownOutlined /> : <UpOutlined />}
                        <Avatar 
                          size={24} 
                          style={{ 
                            backgroundColor: group.platform.color,
                            marginLeft: '8px',
                            marginRight: '8px'
                          }}
                        >
                          {group.platform.name[0]}
                        </Avatar>
                        <Text strong style={{ flex: 1 }}>
                          {group.platform.name}
                        </Text>
                        <Text style={{ color: '#8c8c8c', fontSize: '12px' }}>
                          ({group.accounts.length})
                        </Text>
                      </div>
                      
                      {/* 账号列表 */}
                      {!isCollapsed && (
                        <div style={{ paddingLeft: '8px' }}>
                          {group.accounts.map(account => renderAccountCard(account))}
                        </div>
                      )}
                    </div>
                  );
                })
              )}
            </div>
          </Card>
        </Col>
        
        {/* 右侧内置浏览器区域 */}
        <Col span={16} style={{ display: 'flex', flexDirection: 'column' }}>
          <Card 
            title="内置浏览器" 
            style={{ 
              flex: 1,
              display: 'flex',
              flexDirection: 'column'
            }} 
            bodyStyle={{ 
              padding: '16px',
              flex: 1,
              display: 'flex',
              flexDirection: 'column',
              minHeight: 0,  // 允许内容区域正确收缩
              overflow: 'hidden'
            }}
          >
            <div style={{ 
              flex: 1,
              border: '1px solid #d9d9d9', 
              borderRadius: '6px', 
              backgroundColor: '#fafafa', 
              display: 'flex',
              flexDirection: 'column',
              minHeight: 0,  // 确保容器能够正确收缩
              overflow: 'hidden' 
            }}>
              {browserTabs.length === 0 ? (
                <div style={{ height: '100%', display: 'flex', alignItems: 'center', justifyContent: 'center', color: '#999' }}>
                  <div style={{ textAlign: 'center' }}>
                    <GlobalOutlined style={{ fontSize: '48px', marginBottom: '16px' }} />
                    <p>选择账号进行登录，浏览器将在此处显示</p>
                  </div>
                </div>
              ) : (
                <Tabs
                  type="editable-card"
                  activeKey={activeTabKey}
                  onChange={setActiveTabKey}
                  onEdit={(targetKey, action) => {
                    if (action === 'remove') {
                      const newTabs = browserTabs.filter(tab => tab.key !== targetKey);
                      setBrowserTabs(newTabs);
                      if (targetKey === activeTabKey && newTabs.length > 0) {
                        setActiveTabKey(newTabs[0].key);
                      } else if (newTabs.length === 0) {
                        setActiveTabKey('');
                      }
                    }
                  }}
                  style={{ 
                    flex: 1,
                    display: 'flex',
                    flexDirection: 'column',
                    minHeight: 0,  // 允许Tabs组件正确收缩
                    overflow: 'hidden',
                    height: '100%',  // 明确设置高度为100%
                    backgroundColor: '#fff'  // 确保背景色一致
                  }}
                  tabBarStyle={{ 
                    margin: 0, 
                    padding: '0 8px',  // 添加少量内边距提升视觉效果
                    flexShrink: 0,  // 防止标签栏被压缩
                    backgroundColor: '#fafafa',  // 标签栏背景色
                    borderBottom: '1px solid #d9d9d9'  // 添加分隔线
                  }}
                >
                  {browserTabs.map(tab => (
                    <Tabs.TabPane 
                      tab={tab.title} 
                      key={tab.key} 
                      style={{ 
                        height: '100%',  // 明确设置TabPane高度为100%
                        display: 'flex',
                        flexDirection: 'column',
                        padding: 0, 
                        margin: 0
                      }}
                    >
                      <div style={{ 
                        width: '100%',
                        height: '100%',  // 明确设置容器高度为100%
                        position: 'relative',
                        padding: 0, 
                        margin: 0,
                        overflow: 'hidden',  // 防止内容溢出
                        backgroundColor: '#fff',  // 容器背景色
                        borderRadius: '0 0 6px 6px'  // 底部圆角与Card保持一致
                      }}>
                        {/* 加载状态指示器 */}
                        {webviewLoading[tab.key] && (
                          <div style={{
                            position: 'absolute',
                            top: '50%',
                            left: '50%',
                            transform: 'translate(-50%, -50%)',
                            zIndex: 1000,
                            backgroundColor: 'rgba(255, 255, 255, 0.9)',
                            padding: '20px',
                            borderRadius: '8px',
                            boxShadow: '0 4px 12px rgba(0, 0, 0, 0.1)',
                            display: 'flex',
                            flexDirection: 'column',
                            alignItems: 'center',
                            gap: '12px'
                          }}>
                            <Spin size="large" />
                            <Text style={{ color: '#666', fontSize: '14px' }}>正在加载页面...</Text>
                          </div>
                        )}
                        
                        {/* 错误状态指示器 */}
                        {webviewError[tab.key] && (
                          <div style={{
                            position: 'absolute',
                            top: '50%',
                            left: '50%',
                            transform: 'translate(-50%, -50%)',
                            zIndex: 1000,
                            backgroundColor: '#fff',
                            padding: '30px',
                            borderRadius: '8px',
                            boxShadow: '0 4px 12px rgba(0, 0, 0, 0.1)',
                            display: 'flex',
                            flexDirection: 'column',
                            alignItems: 'center',
                            gap: '16px',
                            textAlign: 'center'
                          }}>
                            <div style={{ fontSize: '48px', color: '#ff4d4f' }}>⚠️</div>
                            <Text style={{ color: '#666', fontSize: '16px' }}>页面加载失败</Text>
                            <Button 
                              type="primary" 
                              onClick={() => {
                                setWebviewError(prev => ({...prev, [tab.key]: false}));
                                setWebviewLoading(prev => ({...prev, [tab.key]: true}));
                                setWebviewKey(prev => prev + 1);
                              }}
                            >
                              重新加载
                            </Button>
                          </div>
                        )}
                        
                        {React.createElement('webview', {
                          key: `${tab.key}-${webviewKey}`,  // 使用组合key确保webview在窗口大小变化时重新渲染
                          src: tab.url,
                          style: { 
                            position: 'absolute',
                            top: 0,
                            left: 0,
                            width: '100%',
                            height: '100%',
                            border: 'none',
                            display: 'block',
                            backgroundColor: '#fff',  // 设置背景色确保webview可见
                            borderRadius: '0 0 6px 6px',  // 与容器保持一致的圆角
                            opacity: webviewLoading[tab.key] ? 0.3 : 1,  // 加载时降低透明度
                            transition: 'opacity 0.3s ease'  // 平滑过渡效果
                          },
                          nodeintegration: 'false',  // 修复：webview使用字符串属性
                          webpreferences: 'contextIsolation=true,enableRemoteModule=false,sandbox=true',
                          useragent: 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36',  // 设置专业的用户代理
                          partition: 'persist:webview',  // 使用持久化分区提升性能
                          ref: (webview: any) => {
                            if (webview) {
                              // 避免重复设置事件监听器，检查是否已经设置过
                              if (!(webview as any)._eventListenersSet) {
                                // 标记已设置事件监听器，防止重复设置
                                (webview as any)._eventListenersSet = true;
                                
                                // 设置初始加载状态（只在首次设置时执行）
                                setWebviewLoading(prev => ({...prev, [tab.key]: true}));
                                setWebviewError(prev => ({...prev, [tab.key]: false}));
                                
                                // 监听webview加载事件
                                const handleLoadStart = () => {
                                  setWebviewLoading(prev => ({...prev, [tab.key]: true}));
                                  setWebviewError(prev => ({...prev, [tab.key]: false}));
                                };
                                
                                const handleLoadStop = () => {
                                  setWebviewLoading(prev => ({...prev, [tab.key]: false}));
                                };
                                
                                const handleLoadAbort = () => {
                                  setWebviewLoading(prev => ({...prev, [tab.key]: false}));
                                  setWebviewError(prev => ({...prev, [tab.key]: true}));
                                };
                                
                                // 添加事件监听器
                                webview.addEventListener('loadstart', handleLoadStart);
                                webview.addEventListener('loadstop', handleLoadStop);
                                webview.addEventListener('loadabort', handleLoadAbort);
                                
                                // 设置定时器作为备用方案
                                const loadingTimer = setTimeout(() => {
                                  setWebviewLoading(prev => ({...prev, [tab.key]: false}));
                                }, 10000); // 10秒后自动取消加载状态
                                
                                // 存储清理函数到webview元素上
                                (webview as any)._cleanup = () => {
                                  webview.removeEventListener('loadstart', handleLoadStart);
                                  webview.removeEventListener('loadstop', handleLoadStop);
                                  webview.removeEventListener('loadabort', handleLoadAbort);
                                  clearTimeout(loadingTimer);
                                  (webview as any)._eventListenersSet = false;
                                };
                              }
                            }
                          }
                        })}
                      </div>
                    </Tabs.TabPane>
                  ))}
                </Tabs>
              )}
            </div>
          </Card>
        </Col>
      </Row>

      <Modal
        title={`扫码登录 - ${platforms.find(p => p.id === selectedPlatform)?.name}`}
        open={qrModalVisible}
        onCancel={() => {
          setQrModalVisible(false);
          setScanning(false);
        }}
        footer={null}
        width={400}
      >
        <div style={{ textAlign: 'center', padding: '20px' }}>
          {qrData ? (
            <>
              <QRCode
                value={qrData.qrCode}
                size={256}
                style={{ marginBottom: 16 }}
              />
              <p>请使用{platforms.find(p => p.id === selectedPlatform)?.name}扫描二维码登录</p>
              <Spin spinning={scanning} tip="等待扫码..." />
            </>
          ) : (
            <Spin size="large" />
          )}
        </div>
      </Modal>

      {/* 添加账号模态框 */}
      <Modal
        title="添加账号"
        open={addAccountModalVisible}
        onOk={handlePlatformConfirm}
        onCancel={() => {
          setAddAccountModalVisible(false);
          setSelectedPlatformForAdd('');
        }}
        okText="确定"
        cancelText="取消"
        width={400}
      >
        <div style={{ padding: '20px 0' }}>
          <Row gutter={[16, 16]}>
            <Col span={24}>
              <p style={{ marginBottom: 16, fontSize: 14, color: '#666' }}>
                <GlobalOutlined style={{ marginRight: 8 }} />
                选择要登录的平台，将使用内置浏览器打开平台网站进行登录
              </p>
            </Col>
            <Col span={24}>
              <Select
                style={{ width: '100%' }}
                placeholder="请选择平台"
                value={selectedPlatformForAdd}
                onChange={setSelectedPlatformForAdd}
                size="large"
              >
                {platforms.map(platform => (
                  <Select.Option key={platform.id} value={platform.id}>
                    <Space>
                      <Avatar 
                        size="small" 
                        style={{ backgroundColor: platform.color }}
                      >
                        {platform.name[0]}
                      </Avatar>
                      {platform.name}
                    </Space>
                  </Select.Option>
                ))}
              </Select>
            </Col>
          </Row>
        </div>
      </Modal>
    </div>
  );
};

// 使用错误边界包装的组件
const WrappedAccountsPage: React.FC = () => {
  return (
    <ErrorBoundary>
      <AccountsPage />
    </ErrorBoundary>
  );
};

export default WrappedAccountsPage;
